package com.graduate.twentyone.util.shiro;

import com.graduate.twentyone.domain.Promission;
import com.graduate.twentyone.domain.Users;
import com.graduate.twentyone.mapper.UsersMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class MyRealm extends AuthorizingRealm {

    @Autowired
    UsersMapper usersMapper;


    //获取当前用户的身份
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname = authenticationToken.getPrincipal().toString();


//        通过用户名查找该用户的信息
        Users user = usersMapper.login(uname);
//        System.out.println("asdsdsdsdsdsd："+user);
        //返回认证信息对象
        if (user != null) {
            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUname(), user.getPwd(), "myRealm");
            return info;

        }
        return null;
    }


    //    获取当前用户的所有权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        获取权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

//        获取用户名
        String uname = (String) principalCollection.getPrimaryPrincipal();
//      获取用户的身份
        String loginrname = usersMapper.loginrname(uname);
//        添加进去
        info.addRole(loginrname);

//        获取用户的权限
        List<Promission> loginpro = usersMapper.loginpro(uname);
//      遍历添加
        for (int i = 0; i < loginpro.size(); i++) {
//            System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
//            System.out.println(loginpro.get(i).getPname());
            info.addStringPermission(loginpro.get(i).getPname());
        }
        return info;
    }

}
